<?php
/**
 * @title 34. 在排序数组中查找元素的第一个和最后一个位置 - 二分
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function searchRange($nums, $target) {
        $len = count($nums);
        $left = 0;
        $right = $len-1;

        /**
         * @since 2020-07-21 查找左边界
         */
        $l = null;
        while($left<=$right){
            $mid = ($left+$right)>>1;
            $val = $nums[$mid];

            if($target <= $val){
                if($target == $val){
                    $l = $mid;
                } else {}
                $right = $mid-1;
            } else {
                $left = $mid+1;
            }
        }

        /**
         * @since 2020-07-21 未找到左边界
         */
        if($l === null){
            return [-1, -1];
        } else {}

        /**
         * @since 2020-07-21 查找有边界
         */
        $r = null;
        $right = $len-1;
        $left = $l+1;
        while($left <= $right){
            $mid = ($left+$right)>>1;
            $val = $nums[$mid];

            if($target >= $val){
                if($target == $val){
                    $r = $mid;
                } else {}
                $left = $mid+1;
            } else {
                $right = $mid-1;
            }
        }

        /**
         * @return
         */
        if($r === null){
            return [$l, $l];
        } else {
            return [$l, $r];
        }
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.04_6.php
 */
$datas = [
    [[5,7,7,8,8,10], 8],
    [[5,7,7,8,8,10], 6],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->searchRange($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
